﻿using FlaUIAutomation.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;

namespace Service
{
    /// <summary>
    /// 
    /// </summary>
    public class QWenService
    {
        public Message Generation(List<MessagesItem> list)
        {
            QWenRequestGeneration wenGeneration = new QWenRequestGeneration
            {
                input = new Input
                {
                    messages = list,
                },
                model = "qwen-max",
                parameters = new Parameters { result_format = "message" }
            };
            var content = Newtonsoft.Json.JsonConvert.SerializeObject(wenGeneration);
 
            var result = new RequestService().PostJson("https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation", content);
            WriteLog(result);

            var resultModel = JsonConvert.DeserializeObject<QWenResponseGeneration>(result);

            return resultModel.output.choices[0].message;
        }


         void WriteLog(string Data)
        {
            try
            {
                //获取当前系统时间
                string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                //日志内容
                string write_content = $"\r\n\r\n\r\n  {time}  \r\n\r\n  {Data} ";
                //需要用户自定义日志实现形式
                Console.WriteLine(write_content);
                string fileName = DateTime.Now.ToString("yyyyMMddHH") + ".txt";
                string urlPath = $"LogsAI/" + DateTime.Now.ToString("yyyyMMdd") + "/" + fileName; // 
                string filePath = AppDomain.CurrentDomain.BaseDirectory + urlPath; // 文件路径
                string directoryName = Path.GetDirectoryName(filePath);
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }
                FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write);
                //获得字节数组
                byte[] data = System.Text.Encoding.Default.GetBytes(write_content);
                //开始写入
                fs.Write(data, 0, data.Length);
                //清空缓冲区、关闭流
                fs.Flush();
                fs.Close();
            }
            catch (Exception ex)
            {
                string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            }
        }

    }
}